import useRoute from '@/hooks/useRoute';
import { PageContainer } from '@ant-design/pro-layout';
import { Breadcrumb, Spin } from 'antd';
import type { FC, ReactNode } from 'react';
import { useAccess, useModel } from 'umi';

import styles from './style.less';

type TProps = {
  loading?: boolean;
  extra?: string | ReactNode;
  children?: any;
};

const CommonPageContainer: FC<TProps> = (props) => {
  const { loading = false, children, extra, ...restProps } = props;
  const { path = '', breadcrumb } = (useRoute() || {}) as any;
  const { initialState } = useModel('@@initialState');
  const { menuKeyMap } = initialState || {};
  const access = useAccess();

  const renderBreadcrumbs = () => {
    let arrBreadList = [];
    const currentRoute: TMenuItem = (menuKeyMap || {})[path];
    const { breadcrumbs } = currentRoute || {};
    if (!access.isSuperAdmin && breadcrumbs && breadcrumbs.length) {
      arrBreadList = breadcrumbs.map((obj) => ({
        name: obj.name,
        path: null,
        // path: obj.url,
      }));
      arrBreadList = [
        {
          name: '首页',
          path: null,
        },
        ...arrBreadList,
      ];
    } else {
      const arrPathList = path.split('/').map((item: string) => `${item}`);
      arrBreadList = arrPathList.map((item: any, index: number) => {
        const permissionTree = {};
        const arrList = arrPathList.slice(0, index + 1);
        let retPath = arrList.join('/');
        retPath = retPath ? retPath : '/';
        let name = breadcrumb[retPath]?.name;
        name = name ? name : '首页';
        // 跳转路由，如果没有注册component，则不执行跳转操作（特殊情况/可跳转）
        const pathReal =
          permissionTree[retPath]?.component || retPath === '/' ? `#${retPath}` : null;
        return { name, path: pathReal };
      });
    }

    return (
      <div className={styles.headerBreadcrumbWrap}>
        <Breadcrumb className="text-noselect ">
          {arrBreadList &&
            arrBreadList.map((item: any, index: any) => (
              <Breadcrumb.Item
                key={`header-breadcrumb-${index}`}
                {...(item.path && { href: item.path })}
              >
                {item.name}
              </Breadcrumb.Item>
            ))}
        </Breadcrumb>
        {extra ? (
          <div className={styles.headerExtraWrap}>
            {typeof extra === 'string' ? (
              <div className={styles.headerExtraContent}>{extra}</div>
            ) : (
              extra
            )}
          </div>
        ) : null}
      </div>
    );
  };

  return (
    <PageContainer
      breadcrumbRender={() => renderBreadcrumbs()}
      header={{ title: false, ghost: true }}
      {...restProps}
    >
      <Spin spinning={loading}>{children}</Spin>
    </PageContainer>
  );
};

export default CommonPageContainer;
